package net.zjitc.reggiebymeme.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import net.zjitc.reggiebymeme.common.R;
import net.zjitc.reggiebymeme.entity.Employee;
import net.zjitc.reggiebymeme.service.EmployeeService;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    @PostMapping("/login")
    public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee) {
        //1、将⻚⾯提交的密码password进⾏md5加密处理
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        //2、根据⻚⾯提交的⽤户名username查询数据库
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername, employee.getUsername());
        Employee emp = employeeService.getOne(queryWrapper);
        //再输出一下 看结果
        log.info("在数据库中查询到结果：" + emp);
        //3、如果没有查询到则返回登录失败结果
        if (emp == null) {
            return R.error("登录失败");
        }
        //4、密码⽐对，如果不⼀致则返回登录失败结果
        if (!emp.getPassword().equals(password)) {
            return R.error("登录失败");
        }
        //5、查看员⼯状态，如果为已禁⽤状态，则返回员⼯已禁⽤结果
        if (emp.getStatus() == 0) {
            return R.error("账号已禁⽤");
        }
        //6、登录成功，将员⼯id存⼊Session并返回登录成功结果
        request.getSession().setAttribute("employee", emp.getId());
        return R.success(emp);
    }

    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request) {
        //7 当用户退出登录后，清理Session中保存的当前登录员⼯的id
        request.getSession().removeAttribute("employee");
        return R.success("退出成功");
    }

    @PostMapping("/add")
    public R<String> save(HttpServletRequest request, @RequestBody Employee employee) {
        log.info("新增的员⼯，员⼯的信息为：{}", employee.toString());
        //并设置初始密码为12345 还要用md5加密处理
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());

        Long empId = (Long) request.getSession().getAttribute("employee");
        //这波啊 是要拿到现在已登录的用户的ID啦
        employee.setCreateUser(empId);
        employee.setUpdateUser(empId);
        employeeService.save(employee);
        return R.success("新增员⼯成功");
        //返回值类型是String 相互呼应
        //员工分页查询
    }

    @GetMapping("/page")
    public R<IPage<Employee>> page ( @RequestParam("page") int currentPage,
                                     @RequestParam("pageSize") int pageSize,
                                     @RequestParam(value = "name", required = false) String name){
        log.info("查询请求：" + currentPage + "," + pageSize + "," + name);

        IPage<Employee> page = new Page<>(currentPage, pageSize);
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(Strings.isNotEmpty(name), Employee::getName, name);
        employeeService.page(page, wrapper);
        log.info(page.getRecords().toString());
        return R.success(page);
    }

    @PostMapping("/update")
    public  R<String> update(HttpServletRequest request,@RequestBody Employee employee){
        log.info(employee.toString());
        Long empId = (Long)request.getSession().getAttribute("employee");
        employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser(empId);
        employeeService.updateById(employee);
        return R.success("修改员⼯信息成功");
    }
    @GetMapping("/{id}")
    public R<Employee> getById(@PathVariable Long id){
        log.info("根据id查询员⼯信息");
        Employee employee = employeeService.getById(id);
        if(employee != null){
            return R.success(employee);
        }
        return R.error("未查询到该员⼯信息");
    }
}